<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Jobs\Wechat\RecordMsg;
use App\Models\Wechat\Record\Msg;

class WechatController extends Controller
{
	var $app;

	var $openid;

    var $message;

	
	public function __construct(){
		$this->app = app('wechat.official_account');
	}

	public function entrance(){
        
        $this->app->server->push(function($message){
            $this->message     = $message;
            $msg = new Msg();
            $msg->fromUserName = $this->message['FromUserName'];
            $msg->toUserName   = $this->message['ToUserName'];
            $msg->msgId        = $this->message['MsgId'];
            $msg->msgType      = $this->message['MsgType'];
            $msg->created_at   = date('Y-m-d H:i:s',$this->message['CreateTime']);
            $result = '';
            switch ($this->message['MsgType']) {
            	case 'event':
	            	$result = $this->event();
                    break;
	            case 'text':
                    $msg->content = trim($this->message['Content']);
                    $msg->save();
	            	$result = $this->text();
	                break;
	            case 'image':
                    $msg->mediaId = $this->message['MediaId'];
                    $msg->mediaUrl = $this->message['PicUrl'];
		            break;
		        case 'voice':
                    $msg->mediaId = $this->message['MediaId'];
                    $msg->mediaFormat = $this->message['Format'];
		            break;
		        case 'video':
                    $msg->mediaId = $this->message['MediaId'];
                    $msg->thumbMediaId = $this->message['ThumbMediaId'];
		            break;
            }
            $msg->save();
            dispatch(new RecordMsg());
            return $result;
        });
        
        return $this->app->server->serve();
    }

    /**
     * 事件处理
     * @return [type] [description]
     */
    private function event(){
        $eventController = new Wechat\EventController($this->message,$this->app);
        return $eventController->entrance();
    }

    /**
     * 文字消息
     * @return [type] [description]
     */
    private function text(){
    	$textController = new Wechat\TextController($this->message,$this->app);
    	return $textController->entrance();
    }

}
